import { useNavigate } from 'react-router'
import { Button, message, Popover, Space, Tooltip } from 'antd'
import Icon from '@ant-design/icons'

import { CusTable } from '@/components/CusTable'
import { addAGCellTexty } from '@oBiz/components/addTexty'
import { Users } from '@oBiz/components/User'
import { useCountries } from '@oBiz/hooks/SWRApi/useCountries'
import { COMMENT_ID } from '@oBiz/TrackOrder/Detail/utils'
import { useBoundStore } from '@oBiz/TrackOrder/List/store'
import { aptPostCreateShippingOrders } from '../apis'
import { IconTypeIcon } from '../components'
import { TCellParams } from '../interface'
import CommentIcon from '@/assets/icons/comment.svg?react'
import DetailIcon from '@/assets/icons/detail.svg?react'
import SendIcon from '@/assets/icons/send.svg?react'

const CountryCell = ({ value }: TCellParams<'countryId'>) => {
  const { data } = useCountries()
  if (value == null) return
  return data?.idMap?.[value]?.chineseName ?? value
}

const BoxesCell = ({ value }: TCellParams<'boxes'>) => {
  if (value?.length == null) return
  const list = value.map(d => d.products).flat()
  if (!list.length) return
  return (
    <Popover
      destroyTooltipOnHide
      content={
        <div style={{ maxHeight: 195, overflow: 'auto' }}>
          <CusTable
            style={{ width: 500 }}
            dataSource={list}
            rowKey="boxId"
            columns={[
              { title: '中文品名', dataIndex: 'cname' },
              { title: '英文品名', dataIndex: 'ename' },
              { title: 'SKU', dataIndex: 'sku' },
              { title: 'FNSKU', dataIndex: 'fnsku' },
            ]}
          />
        </div>
      }
    >
      <a>
        {list[0].cname || list[0].ename || '--'}
        {list.length > 1 && `(${list.length})`}
      </a>
    </Popover>
  )
}

const ActionCell = ({ data }: TCellParams<'recordId'>) => {
  const getData = useBoundStore(v => v.getData)
  const navigate = useNavigate()
  if (data == null) return
  return (
    <>
      <Tooltip title="创建物流订单">
        <Button
          disabled={!!data.createShippingOrderStatus}
          type="link"
          icon={<Icon component={SendIcon} />}
          onClick={async () => {
            const result = await aptPostCreateShippingOrders({ waybillNos: [data.waybillNo] })
            if (result.succeedWaybillNos.length > 0) {
              message.success('创建物流订单成功，请去牛迈系统发布轨迹')
              getData()
            } else {
              message.warning(
                <>
                  {result.failedWaybillMesses.map(item => (
                    <div key={item.waybillNo}>{item.message}</div>
                  ))}
                </>,
              )
            }
          }}
        />
      </Tooltip>
      <Tooltip title="详情">
        <Button
          type="link"
          icon={<Icon component={DetailIcon} />}
          onClick={() => {
            navigate(`/biz/trackOrder/list/detail/${data.waybillNo}`)
          }}
        />
      </Tooltip>
      <Tooltip title="留言">
        <Button
          type="link"
          icon={<Icon component={CommentIcon} />}
          onClick={() => {
            navigate(`/biz/trackOrder/list/detail/${data.waybillNo}#${COMMENT_ID}`)
          }}
        />
      </Tooltip>
    </>
  )
}

export const Cell = (p: TCellParams) => {
  const { data } = p
  const { field } = p.colDef || {}
  switch (field) {
    case '标签': {
      const errorNode = (
        <Tooltip title={data?.errorType === 1 && '异常或异常处理中'}>
          <IconTypeIcon value={3} active={data?.errorType === 1} />
        </Tooltip>
      )
      return $APP === 'TMS' ? (
        <Space size={4}>
          <Tooltip title={data?.timeIconType === 1 && '超时'}>
            <IconTypeIcon value={1} active={data?.timeIconType === 1} />
          </Tooltip>
          <Tooltip title={data?.readType === 1 && '未读'}>
            <IconTypeIcon value={2} active={data?.readType === 1} />
          </Tooltip>
          {errorNode}
        </Space>
      ) : (
        <Space size={4}>
          <Tooltip title={data?.emailType === 1 && '待发送'}>
            <IconTypeIcon value={4} active={data?.emailType === 1} />
          </Tooltip>
          {errorNode}
        </Space>
      )
    }
    case 'transferCodes': {
      const { value } = p as TCellParams<'transferCodes'>
      if (!value?.length) return
      return (
        <Popover
          destroyTooltipOnHide
          content={
            value.length > 1 && (
              <div style={{ maxHeight: 200, minWidth: 130, overflow: 'auto' }}>
                {value.map(d => (
                  <div key={d}>{d}</div>
                ))}
              </div>
            )
          }
        >
          <a>
            {value[0]}
            {value.length > 1 && `(${value.length})`}
          </a>
        </Popover>
      )
    }
    case 'countryId': {
      return <CountryCell {...(p as TCellParams<'countryId'>)} />
    }
    case 'staffInfoList': {
      const { value } = p as TCellParams<'staffInfoList'>
      if (!value) return
      return (
        <Users
          itemSize={31}
          dataList={value.map(v => ({
            avatar: v.user.avatar,
            name: v.user.name || v.user.englishName,
            tagName: { 1: '业务员', 2: '跟单员' }[v.staffType],
            phone: v.user.phone,
          }))}
        />
      )
    }
    case 'boxes': {
      return <BoxesCell {...(p as TCellParams<'boxes'>)} />
    }
    case 'recordId': {
      return <ActionCell {...(p as TCellParams<'recordId'>)} />
    }
    default: {
      return addAGCellTexty(p)
    }
  }
}
